package persistence

import (
	"context"
	"time"

	"Data-API-MCP/backend/internal/domain/entity"
	"Data-API-MCP/backend/internal/domain/repository"

	"gorm.io/gorm"
)

// statisticsRepository 统计仓库实现
type statisticsRepository struct {
	db *gorm.DB
}

// NewStatisticsRepository 创建统计仓库实例
func NewStatisticsRepository(db *gorm.DB) repository.StatisticsRepository {
	return &statisticsRepository{
		db: db,
	}
}

// RecordAPICall 记录API调用
func (r *statisticsRepository) RecordAPICall(ctx context.Context, call *entity.APICall) error {
	return r.db.WithContext(ctx).Create(call).Error
}

// GetAPICallStats 获取API调用统计
func (r *statisticsRepository) GetAPICallStats(ctx context.Context, startTime time.Time) (map[string]interface{}, error) {
	var stats map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.APICall{}).
		Where("request_time >= ?", startTime).
		Select("COUNT(*) as total_calls, AVG(duration) as avg_duration, COUNT(CASE WHEN status = 1 THEN 1 END) as success_count").
		Scan(&stats).Error
	return stats, err
}

// GetAPICallDetail 获取API调用详情
func (r *statisticsRepository) GetAPICallDetail(ctx context.Context, id string) (*entity.APICall, error) {
	var call entity.APICall
	err := r.db.WithContext(ctx).Where("id = ?", id).First(&call).Error
	return &call, err
}

// GetAPIErrorStats 获取API错误统计
func (r *statisticsRepository) GetAPIErrorStats(ctx context.Context, startTime time.Time) (map[string]interface{}, error) {
	var stats map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.APICall{}).
		Where("request_time >= ? AND status = 0", startTime).
		Select("COUNT(*) as error_count, error_msg").
		Group("error_msg").
		Scan(&stats).Error
	return stats, err
}

// GetAPIPerformance 获取API性能统计
func (r *statisticsRepository) GetAPIPerformance(ctx context.Context, startTime time.Time) (map[string]interface{}, error) {
	var stats map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.APICall{}).
		Where("request_time >= ?", startTime).
		Select("AVG(duration) as avg_response_time, MAX(duration) as max_response_time, MIN(duration) as min_response_time").
		Scan(&stats).Error
	return stats, err
}

// GetAPICallLogs 获取API调用日志
func (r *statisticsRepository) GetAPICallLogs(ctx context.Context, apiID string, startTime, endTime time.Time) ([]*entity.APICall, error) {
	var calls []*entity.APICall
	err := r.db.WithContext(ctx).
		Where("api_id = ? AND request_time BETWEEN ? AND ?", apiID, startTime, endTime).
		Order("request_time DESC").
		Find(&calls).Error
	return calls, err
}

// GetDatabaseStats 获取数据库连接统计
func (r *statisticsRepository) GetDatabaseStats(ctx context.Context) (map[string]interface{}, error) {
	var stats map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.DatabaseConnectionStats{}).
		Select("COUNT(*) as total_connections, SUM(connection_count) as total_active_connections").
		Scan(&stats).Error
	return stats, err
}

// GetDBQueryStats 获取数据库查询统计
func (r *statisticsRepository) GetDBQueryStats(ctx context.Context, startTime time.Time) (map[string]interface{}, error) {
	var stats map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.DBQueryLog{}).
		Where("created_at >= ?", startTime).
		Select("COUNT(*) as total_queries, AVG(duration) as avg_duration, COUNT(CASE WHEN status = 'success' THEN 1 END) as success_count").
		Scan(&stats).Error
	return stats, err
}

// GetDBPerformance 获取数据库性能统计
func (r *statisticsRepository) GetDBPerformance(ctx context.Context) (map[string]interface{}, error) {
	var stats map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.DBQueryLog{}).
		Select("AVG(duration) as avg_query_time, MAX(duration) as max_query_time, MIN(duration) as min_query_time").
		Scan(&stats).Error
	return stats, err
}

// GetDBConnectionStats 获取数据库连接统计
func (r *statisticsRepository) GetDBConnectionStats(ctx context.Context) (map[string]interface{}, error) {
	var stats map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.DatabaseConnectionStats{}).
		Select("db_type, COUNT(*) as connection_count, SUM(connection_count) as active_connections").
		Group("db_type").
		Scan(&stats).Error
	return stats, err
}

// RecordDatabaseConnectionStats 记录数据库连接统计
func (r *statisticsRepository) RecordDatabaseConnectionStats(ctx context.Context, stats *entity.DatabaseConnectionStats) error {
	return r.db.WithContext(ctx).Create(stats).Error
}

// GetDatabaseConnectionStats 获取数据库连接统计
func (r *statisticsRepository) GetDatabaseConnectionStats(ctx context.Context, dbType string) ([]*entity.DatabaseConnectionStats, error) {
	var stats []*entity.DatabaseConnectionStats
	err := r.db.WithContext(ctx).
		Where("db_type = ?", dbType).
		Find(&stats).Error
	return stats, err
}

// GetServiceStats 获取服务统计
func (r *statisticsRepository) GetServiceStats(ctx context.Context, serviceID string) (*entity.ServiceStats, error) {
	var stats entity.ServiceStats
	err := r.db.WithContext(ctx).
		Where("service_id = ?", serviceID).
		First(&stats).Error
	return &stats, err
}

// GetServiceHealth 获取服务健康状态
func (r *statisticsRepository) GetServiceHealth(ctx context.Context, serviceID string) (map[string]interface{}, error) {
	var health map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.ServiceStats{}).
		Where("service_id = ?", serviceID).
		Select("status, success_rate, last_check_time").
		Scan(&health).Error
	return health, err
}

// GetTopServices 获取热门服务
func (r *statisticsRepository) GetTopServices(ctx context.Context, limit int) ([]*entity.ServiceStats, error) {
	var services []*entity.ServiceStats
	err := r.db.WithContext(ctx).
		Order("call_count DESC").
		Limit(limit).
		Find(&services).Error
	return services, err
}

// RecordServiceCallLog 记录服务调用日志
func (r *statisticsRepository) RecordServiceCallLog(ctx context.Context, log *entity.ServiceCallLog) error {
	return r.db.WithContext(ctx).Create(log).Error
}

// GetServiceCallLogs 获取服务调用日志
func (r *statisticsRepository) GetServiceCallLogs(ctx context.Context, serviceID string, startTime, endTime time.Time) ([]*entity.ServiceCallLog, error) {
	var logs []*entity.ServiceCallLog
	err := r.db.WithContext(ctx).
		Where("service_id = ? AND created_at BETWEEN ? AND ?", serviceID, startTime, endTime).
		Order("created_at DESC").
		Find(&logs).Error
	return logs, err
}

// GetSystemStatus 获取系统状态
func (r *statisticsRepository) GetSystemStatus(ctx context.Context) (map[string]interface{}, error) {
	var status map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.SystemStatus{}).
		Select("status, uptime, last_update_time").
		Scan(&status).Error
	return status, err
}

// GetSystemResources 获取系统资源使用情况
func (r *statisticsRepository) GetSystemResources(ctx context.Context) (map[string]interface{}, error) {
	var resources map[string]interface{}
	err := r.db.WithContext(ctx).Model(&entity.SystemResources{}).
		Select("cpu_usage, memory_usage, disk_usage, network_usage").
		Scan(&resources).Error
	return resources, err
}

// GetSystemLogs 获取系统日志
func (r *statisticsRepository) GetSystemLogs(ctx context.Context, startTime, endTime time.Time) ([]*entity.SystemLog, error) {
	var logs []*entity.SystemLog
	err := r.db.WithContext(ctx).
		Where("created_at BETWEEN ? AND ?", startTime, endTime).
		Order("created_at DESC").
		Find(&logs).Error
	return logs, err
}
